#include <stdlib.h>
#include <stdio.h>
#include <WinSock2.h>
#include <Ws2tcpip.h>
#include "Common.h"
#include "WorkerThread.h"
#pragma comment(lib, "Common.lib")
#pragma comment(lib, "ws2_32.lib")

#define MAXPAYLOAD 3
#define MAXTHREAD MAXPAYLOAD

HANDLE threadHandles[MAXTHREAD];
HANDLE g_hIOCP;
SOCKET g_listenSocket;
int totalThreadNum = MAXTHREAD;

typedef struct _TPNODEINFO {
	int totalUser;
	TUserInfo* rootUserInfo;
} TPNODEINFO;

void init(void) {
	for (int i=0; i<MAXTHREAD; ++i)
		threadHandles[i] = INVALID_HANDLE_VALUE;
// 
// 	SYSTEM_INFO systemInfo;
// 	GetSystemInfo(&systemInfo);
// 	totalThreadNum = 2*systemInfo.dwNumberOfProcessors;

	WSAData wsaData;
	if( WSAStartup(MAKEWORD(2,2), &wsaData) != 0 ) {
		error("bad startup");
		return;
	}

// 	g_hIOCP = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 0);
	for (int i=0; i<totalThreadNum; ++i) {
		unsigned long id;
// 		HANDLE h = CreateThread(NULL, 0, WorkerThreadIOCP, g_hIOCP, 0, &id);
		HANDLE h = CreateThread(NULL, 0, WorkerThread, NULL, 0, &id);
		threadHandles[i] = h;
	}
}

// void waiting2(void) {
// 	SOCKET acceptSocket;
// 	while(true) {
// 		acceptSocket = WSAAccept(g_listenSocket, NULL, NULL, NULL, 0);
// 		if (acceptSocket == SOCKET_ERROR) error("accepting socket error");
// 		TSocketInfo *socketInfo = tSocketInfo();
// 		g_hIOCP = CreateIoCompletionPort((HANDLE)acceptSocket, g_hIOCP, (ULONG)socketInfo, 0);
// 		int nRet = WSARecv(acceptSocket, &(socketInfo->buf), 1, &(socketInfo->recvBytes),
// 				&(socketInfo->flag), &(socketInfo->overlapped), NULL);
// 		if (nRet == SOCKET_ERROR && (ERROR_IO_PENDING != WSAGetLastError()))
// 			error("WSARecv Failed");
// 	}
// }

void waiting(void) {
	SOCKET acceptSocket;
	char buf[MAXBUFFSIZE];
	memset(buf, 0, MAXBUFFSIZE);
	while (true) {
		acceptSocket = accept(g_listenSocket, NULL, NULL);
		int recvBytes = recv(acceptSocket, buf, MAXBUFFSIZE, 0);
		if (recvBytes < 0) error("recv error.");
		else if (recvBytes == 0) break;
		buf[recvBytes] = 0;
		TOperationInfo opInfo;
		printf("recvByte = %d, buf = '%s'\n", recvBytes, buf);
		sscanf(buf, "%d %d", &opInfo.op, &opInfo.val);
		printf("op = %d, val = %d\n", opInfo.op, opInfo.val);
		switch (opInfo.op) {
		case USER_CONNECT:
			createConnectSocket(PORT2, LOCALHOST, &connectPayloaderSkt);
			break;
		case USER_GETNODE:
			break;
		case USER_RELEASE:
			break;
		case NODE_GETNUM:
			break;
		}

	}
}

int main(void)
{

	init();
	createListenSocket(PORT, &g_listenSocket, true);
	waiting();

	return 0;
}
